﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Client.ClientAdminServer;
using System.Data;

namespace Client
{
    public partial class ClientForm : Form
    {

        private delegate void SetTextCallback(string text, Control textBox);
        private delegate void SetCheckedCallback(bool state, CheckBox checkBox);

        private ClientAdminService clientAdminService;

        public ClientForm()
        {
            InitializeComponent();
            clientAdminService = new ClientAdminService();
            clientAdminService.GetClientInformationCompleted += new GetClientInformationCompletedEventHandler(clientAdminService_GetClientInformationCompleted);
            clientAdminService.AddCreditCompleted += new AddCreditCompletedEventHandler(clientAdminService_AddCreditCompleted);
        }

        void clientAdminService_AddCreditCompleted(object sender, AddCreditCompletedEventArgs e)
        {
            if(e.Result)
            {
                MessageBox.Show("Acreditacion realizada con exito");
            }
            else
            {
                MessageBox.Show("Error realizando la acreditacion");
            }

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            int clientId;
            errorProvider.SetError(txtClientId, string.Empty);

            if (!int.TryParse(txtClientId.Text, out clientId))
            {
                errorProvider.SetError(txtClientId, "El identificador del cliente debe ser un numero entero");
            }
            else
            {
                try
                {
                    clientAdminService.GetClientInformationAsync(clientId);
                }
                catch(Exception ex)
                {
                    MessageBox.Show("Ocurrio un error obteniendo los datos del cliente");
                }
            }
            
        }

        void clientAdminService_GetClientInformationCompleted(object sender, GetClientInformationCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    SetText(e.Result.Name, txtUsername);
                    SetText(e.Result.balance.ToString("0,0.000"), txtBalance);
                    SetChecked(e.Result.IsActive, chkActive);
                    SetChecked(e.Result.Prepaid, chkPrepaid);

                    TripsDataSource.Clear();
                    foreach (TripDTO tripDto in e.Result.Trips)
                    {
                        string status = "Desconocido";
                        switch (tripDto.Status)
                        {
                            case TripStatus.Started:
                                status = "Iniciado";
                                break;
                            case TripStatus.Active:
                                status = "Activo";
                                break;
                            case TripStatus.Ended:
                                status = "Terminado";
                                break;

                        }
                        TripsDataSource.Add(new TripRow()
                        {
                            TripId = tripDto.TripId.ToString(),
                            Charge = tripDto.Charge.ToString("0,0.000"),
                            Distance = tripDto.Distance.ToString("0,0.000"),
                            Status = status
                        });
                    }
                }
                else
                {
                    MessageBox.Show(@"El cliente solicitado no existe en el sistema", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception)
            {
                MessageBox.Show(@"The web service drop an error", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }



        }

        private void SetText(string text, Control textBox)
        {

            if (textBox.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text, textBox });
            }
            else
            {
                textBox.Text = text;
            }
        }

        private void SetChecked(bool state, CheckBox checkBox)
        {

            if (checkBox.InvokeRequired)
            {
                SetCheckedCallback d = new SetCheckedCallback(SetChecked);
                this.Invoke(d, new object[] { state, checkBox });
            }
            else
            {
                checkBox.Checked = state;
            }
        }

        private void btnAddCredit_Click(object sender, EventArgs e)
        {
            int clientId;
            decimal credit;

            errorProvider.SetError(txtClientId,string.Empty);
            errorProvider.SetError(txtCredit, string.Empty);

            if (!int.TryParse(txtCreditClientId.Text, out clientId))
            {
                errorProvider.SetError(txtCreditClientId, "El identificador del cliente debe ser un numero entero");
            }
            else if(!decimal.TryParse(txtCredit.Text,out credit))
            {
                errorProvider.SetError(txtCredit, "El identificador del cliente debe ser un numero decimal");
            }
            else
            {
                try
                {
                    clientAdminService.AddCreditAsync(clientId, credit);
                }
                catch(Exception ex)
                {
                    MessageBox.Show("Ocurrio un error agregando el credito");
                }
            }


        }


    }
}
